/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ctrl;

import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Resource;
import javax.mail.Message.RecipientType;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.naming.NamingException;
import model.BookingBackingBean;
import entities.Booking;
import entities.GuestUser;
import entities.Room;
import hotel.jpa.BookingJpaCtrl;
import hotel.jpa.IBookingJpaCtrl;
import hotel.jpa.IRoomJpaCtrl;
import hotel.jpa.RoomJpaCtrl;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import javax.el.ELContext;
import javax.el.ExpressionFactory;
import javax.el.ValueExpression;
import javax.faces.application.Application;
import javax.faces.bean.ManagedBean;
import javax.faces.context.FacesContext;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.NoSuchProviderException;
import javax.mail.PasswordAuthentication;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 *
 * @author Anton Karlsson
 */
@ManagedBean(name = "confirmControllerBean")
public class ConfirmControllerBean {

    private static final String SMTP_HOST_NAME = "smtp.gmail.com";
    private static final int SMTP_HOST_PORT = 465;
    private static final String SMTP_AUTH_USER = "ninjarobirob@gmail.com";
    private static final String SMTP_AUTH_PWD = "kahlan89";

    public String confirmed(int roomNb) throws ParseException {

        //Using other bean
        FacesContext ctx = FacesContext.getCurrentInstance();
        Application app = ctx.getApplication();
        ELContext ectx = ctx.getELContext();
        ExpressionFactory ef = app.getExpressionFactory();
        ValueExpression ve = ef.createValueExpression(ectx, "#{bookingBackingBean}", BookingBackingBean.class);
        BookingBackingBean db = (BookingBackingBean) ve.getValue(ectx);

        //Get correct room (by roomNb, had prefered ID, but it seems to be wrong 
        //
        EntityManagerFactory emf =
                Persistence.createEntityManagerFactory("hotel_pu");
        IRoomJpaCtrl roomCtrl = new RoomJpaCtrl(null, emf);

        List<Room> ps = roomCtrl.findEntities();
        Room thRoom = null;
        for (Room pr : ps) {
            if (pr.getRoomNb() == roomNb) {
                thRoom = pr;
            }
        }

        //Get right user
        HttpServletRequest req = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
        HttpSession session = req.getSession();

        GuestUser theUser = (GuestUser) session.getAttribute("loginUser");

        //Persist a new booking 
        IBookingJpaCtrl bookingCtrl = new BookingJpaCtrl(null, emf);

        //Get the date today (ex. 2011-10-15)
        Date today = Calendar.getInstance().getTime();

        //Fromdate
        String str = db.getFromDate();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); //please notice the capital M
        Date fromDate = formatter.parse(str);

        //Get the end date of the booking
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(fromDate);
        calendar.add(Calendar.DAY_OF_YEAR, db.getNoOfNights());
        Date endDate = calendar.getTime();


        //Persist a new booking
        Booking b = new Booking(today, fromDate, endDate, thRoom, theUser);

        bookingCtrl.create(b);

        // Send e-mail
        try {
            // Send e-mail
            String message = "This is a confirmation message\n\nName: " + theUser.getName() + "\n\nRoom: " + b.getRoom().getRoomNb() + 
                    "\n\nDate: " + b.getStartDate() + " - " + b.getEndDate();
            sendMail(theUser.getEmail(), "Thank you for booking at Sunshine Hotel", message);
        } catch (MessagingException ex) {
            Logger.getLogger(ConfirmControllerBean.class.getName()).log(Level.SEVERE, null, ex);

            return "/user/confirmation.xhtml?error=mail";
        }

        return "/user/confirmation.xhtml";
    }

    private void sendMail(String email, String subject, String body) throws NoSuchProviderException, MessagingException {
        Properties props = new Properties();

        props.put("mail.transport.protocol", "smtps");
        props.put("mail.smtps.host", SMTP_HOST_NAME);
        props.put("mail.smtps.auth", "true");
        // props.put("mail.smtps.quitwait", "false");

        Session mailSession = Session.getDefaultInstance(props);
        mailSession.setDebug(true);
        Transport transport = mailSession.getTransport();

        MimeMessage message = new MimeMessage(mailSession);
        message.setSubject(subject);
        message.setContent(body, "text/plain");

        message.addRecipient(Message.RecipientType.TO,
                new InternetAddress(email));

        transport.connect(SMTP_HOST_NAME, SMTP_HOST_PORT, SMTP_AUTH_USER, SMTP_AUTH_PWD);

        transport.sendMessage(message,
                message.getRecipients(Message.RecipientType.TO));
        transport.close();

    }
}
